package com.lanou.bookstore.user.dao;


import com.lanou.bookstore.user.domain.User;
import com.lanou.bookstore.util.JDBCUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class LoginDao {

    //能否登录成功
    public boolean canLogin(String username, String password) {
        Connection conn = JDBCUtil.getConn();
        String sql = "SELECT count(*) FROM tb_user WHERE " +
                "username = ? AND password = ?";
        try {
            PreparedStatement statement
                    = conn.prepareStatement(sql);
            statement.setString(1, username);
            statement.setString(2, password);
            ResultSet rs = statement.executeQuery();
            boolean canLogin = false;
            if (rs.next()) {
                int count = rs.getInt(1);
                canLogin = count > 0;
            }
            statement.close();
            rs.close();
            return canLogin;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public User login(String username, String password) {

        try {
            User user = new User();
            Connection conn = JDBCUtil.getConn();
            // 查询数据库
            String sql = "SELECT * FROM tb_user " +
                    "WHERE username = ? AND password = ?";
            PreparedStatement statement
                    = conn.prepareStatement(sql);
            statement.setString(1, username);
            statement.setString(2, password);
            ResultSet rs = statement.executeQuery();
            rs.next();
            // 设置User属性
            String dbUsername = rs
                    .getString("username");
            String dbUseruid=rs.getString("uid");
            user.setUid(dbUseruid)
                    .setUsername(dbUsername)
                    .setPassword("");

            rs.close();
            statement.close();
            return user;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
